package spring.framework.beans.factory.support;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import spring.framework.beans.BeansException;
import spring.framework.beans.PropertyValue;
import spring.framework.beans.factory.DisposableBean;
import spring.framework.beans.factory.InitializingBean;
import spring.framework.beans.factory.config.AutowireCapableBeanFactory;
import spring.framework.beans.factory.config.BeanDefinition;
import spring.framework.beans.factory.config.BeanPostProcessor;
import spring.framework.beans.factory.config.BeanReference;

import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author fun.pengzh
 * @class spring.framework.beans.factory.support.AbstractAutowireCapableBeanFactory
 * @desc
 * @since 2021-10-07
 */
public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory implements AutowireCapableBeanFactory {


    private InstantiationStrategy instantiationStrategy = new CglibSubClassingIntantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition, Object[] args) throws BeansException {

        Object bean = null;
        try {

            //1、生产Bean实例
            bean = createBeanInstance(beanName, beanDefinition, args);
            //2、填充Bean属性、依赖注入
            applyPropertyValues(beanName, bean, beanDefinition);
            //3、执行Bean初始化方法、postProcessor前置和后置方法
            bean = initializeBean(beanName, bean, beanDefinition);

        } catch (BeansException e) {
            throw new BeansException("Create Bean Exception:", e.getCause());
        }

        registerDisposableBeanIfNecessary(beanName,bean,beanDefinition);

        //4、添加到单例池
        addSingleton(beanName, bean);

        return bean;
    }

    /**
     * 按策略生成Bean实例
     */
    protected Object createBeanInstance(String beanName, BeanDefinition beanDefinition, Object[] args) {
        Class beanClass = beanDefinition.getBeanClass();
        Constructor[] constructors = beanClass.getDeclaredConstructors();
        Constructor usedConstructor = null;
        for (Constructor constructor : constructors) {
            if (args != null && constructor.getParameterTypes().length == args.length) {
                usedConstructor = constructor;
                break;
            }
        }
        return getInstantiationStrategy().instantiate(beanName, beanDefinition, usedConstructor, args);
    }

    /**
     * Bean属性填充
     */
    protected void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        PropertyValue[] propertyValues = beanDefinition.getPropertyValues().getPropertyValues();

        for (PropertyValue propertyValue : propertyValues) {
            String name = propertyValue.getName();
            Object value = propertyValue.getValue();
            if (value instanceof BeanReference) {
                BeanReference reference = (BeanReference) value;
                value = getBean(reference.getBeanName());
            }
            BeanUtil.setFieldValue(bean, name, value);
        }
    }

    private Object initializeBean(String beanName, Object bean, BeanDefinition beanDefinition) throws BeansException {
        //1、 执行 BeanPostProcessor before处理
        Object wrappedBean = applyBeanPostProcessorsBeforeInitialization(bean, beanName);
        //2、调用初始化方法
        try {
            invokeInitMethods(beanName, wrappedBean, beanDefinition);
        } catch (Exception e) {
            throw new BeansException("Invocation of init method of bean[" + beanName + "] failed", e);
        }
        //3、 执行 BeanPostProcessor After处理
        wrappedBean = applyBeanPostProcessorsAfterInitialization(bean, beanName);
        return wrappedBean;
    }

    protected void registerDisposableBeanIfNecessary(String beanName, Object bean, BeanDefinition beanDefinition) {
        if (bean instanceof DisposableBean || StrUtil.isNotEmpty(beanDefinition.getDestroyMethodName())) {
            registerDisposableBean(beanName, new DisposableBeanAdapter(bean, beanName, beanDefinition));
        }
    }

    private void invokeInitMethods(String beanName, Object wrappedBean, BeanDefinition beanDefinition) throws Exception {

        //1、执行Bean初始化方法
        if (wrappedBean instanceof InitializingBean) {
            ((InitializingBean) wrappedBean).afterPropertiesSet();
        }
        //2、避免二次初始化
        String initMethod = beanDefinition.getInitMethodName();
        if (StrUtil.isNotBlank(initMethod)) {
            Method method = beanDefinition.getBeanClass().getMethod(initMethod);
            if (method == null) {
                throw new BeansException("Could not find an init method named '" + initMethod + "' on bean with name '" + beanName + "'");
            }
            method.invoke(wrappedBean);
        }
    }

    @Override
    public Object applyBeanPostProcessorsBeforeInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        List<BeanPostProcessor> beanPostProcessors = getBeanPostProcessors();
        for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
            Object current = beanPostProcessor.postProcessBeforeInitialization(existingBean, beanName);
            if (current == null) {
                return result;
            }
            result = current;
        }
        return result;
    }

    @Override
    public Object applyBeanPostProcessorsAfterInitialization(Object existingBean, String beanName) throws BeansException {
        Object result = existingBean;
        List<BeanPostProcessor> beanPostProcessors = getBeanPostProcessors();
        for (BeanPostProcessor beanPostProcessor : beanPostProcessors) {
            Object current = beanPostProcessor.postProcessAfterInitialization(existingBean, beanName);
            if (current == null) {
                return result;
            }
            result = current;
        }
        return result;
    }

    /**
     * getter setter
     */
    public InstantiationStrategy getInstantiationStrategy() {
        return instantiationStrategy;
    }

    public void setInstantiationStrategy(InstantiationStrategy instantiationStrategy) {
        this.instantiationStrategy = instantiationStrategy;
    }
}
